package com.itee.javafx.controls;

import com.itee.core.util.StringCoder;
import javafx.scene.control.TextField;

import java.util.Arrays;

/**
 * Created by gonglei on 14-4-22.
 */
public class LimitedTextField extends TextField {

    public static final int NO_LIMIT = 0;

    private int limit;

    private boolean autoFillZero = false;

    public LimitedTextField() {
        this(NO_LIMIT);
    }

    public LimitedTextField(int limit) {
        this.limit = limit;
    }

    @Override
    public void replaceText(int start, int end, String text) {
        super.replaceText(start, end, text);
        verify();
    }

    @Override
    public void replaceSelection(String text) {
        super.replaceSelection(text);
        verify();
    }

    protected void verify() {
        if (limit > NO_LIMIT) {
            final int length = getText().length();
            if (length > limit) {
                setText(getText().substring(length - limit, length));
                selectRange(limit, limit);
            } else {
                if (autoFillZero) {
                    String s = StringCoder.fillZeroLeft(getText(), limit);
                    if (s.equals(emptyString())) {
                        clear();
                        selectRange(0, 0);
                    } else {
                        setText(s);
                        selectRange(limit, limit);
                    }
                }
            }
        }
    }

    private String emptyString() {
        char[] emptyChars = new char[limit];
        Arrays.fill(emptyChars, '0');
        return new String(emptyChars);
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public boolean isAutoFillZero() {
        return autoFillZero;
    }

    public void setAutoFillZero(boolean autoFillZero) {
        this.autoFillZero = autoFillZero;
    }
}
